
const { Service } = require("egg");
const { Op } = require("sequelize");

class TopicLessonVideoLogService extends Service {
  calcDuration(arr) {
    let duration = 0;
    if (Array.isArray(arr)) {
      arr.forEach(item => {
        const [start, end] = item;
        if (typeof end === 'number' && typeof start === 'number') {
          duration += end - start;;

        }
      });
    }
    return duration;
  }


  async getUserDuration({ userId, videoIds }) {
    let arr = await this.app.model.TopicLessonVideoLogs.findAll({
      where: {
        userId: userId,
        videoId: {
          [Op.in]: videoIds
        }
      },
      attributes: ['userId', 'videoId', 'datas'],
      raw: true,
    });
    if (Array.isArray(arr)) {
      return arr.map((item) => {
        return {
          ...item,
          duration: this.calcDuration(item.datas)
        }
      })
    }
    return []
  }

  async createOrUpdate({ videoId, userId, datas }) {
    let log = await this.app.model.TopicLessonVideoLogs.findOne({
      where: { videoId, userId },
    });

    let logData = [];

    if (!log) {
      log = await this.app.model.TopicLessonVideoLogs.create({
        videoId, userId, datas: [datas]
      });
      logData = datas;

    } else {
      const existingDatas = log.datas || [];
      const newData = this.handleNewPlayTime(datas, existingDatas);
      await log.update({ datas: newData });
      logData = newData;
    }
    return logData
  }


  /**
  * 处理新的播放时间数据，避免重复记录，合并有交集的时间段
  * @param {Array} newPlayTime - 新的播放时间数组，每个元素为[start, end]
  * @param {Array} existingDatas - 已有的播放时间数据数组
  * @returns {Array} 更新后的播放时间数据数组
  */
  handleNewPlayTime(newPlayTime, existingDatas) {
    // 验证newPlayTime是一个有效的数组
    if (!Array.isArray(newPlayTime) || newPlayTime.length !== 2) {
      return existingDatas;
    }


    const newStart = newPlayTime[0];
    const newEnd = newPlayTime[1];

    // 用于存放最终的播放时间数据
    const result = [];

    for (let i = 0; i < existingDatas.length; i++) {
      const [start, end] = existingDatas[i];

      // 检查新时间段是否完全包含于现有时间段内
      if (newStart >= start && newEnd <= end) {
        // 完全包含，忽略新时间段
        result.push([start, end]);
      } else if (
        // 检查是否有交集
        (newStart <= start && newEnd >= start) ||
        (newStart >= start && newStart <= end) ||
        (newStart <= end && newEnd >= end)
      ) {
        // 有交集，合并时间段
        const mergedStart = Math.min(start, newStart);
        const mergedEnd = Math.max(end, newEnd);
        result.push([mergedStart, mergedEnd]);
      } else {
        // 没有交集，保留现有时间段
        result.push([start, end]);
      }
    }

    // 检查新时间段是否需要添加
    if (!result.some(([start, end]) => newStart >= start && newEnd <= end)) {
      result.push(newPlayTime);
    }


    console.log("result", result)

    const uniqueResult = Array.from(new Set(result.map(item => JSON.stringify(item))), item => JSON.parse(item))
      .sort((a, b) => a[0] - b[0]);

    return uniqueResult;
  }
}

module.exports = TopicLessonVideoLogService;